﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using NetCore.BLL;
using NetCore.Model;

namespace NetCore.Web.Controllers
{
   
    public class AccountController : BaseController
    {
        public IUserService service { get; set; }
        public IEmailService eService { get; set; }
        public IActionResult Index()
        {
            ViewData["BindType"] = "0";
            return View("Register");
        }

        #region 密码修改

        /// <summary>
        /// 忘记密码
        /// </summary>
        /// <param name="UserName"></param>
        /// <returns></returns>
        public async Task<IActionResult> Forgotpassword(string userName, string verCode)
        {
            ViewData["UserName"] = userName;
            if (IsPost)
            {
                string oldVerCode = HttpContext.Session.Get<string>(ConfigHelper.RESET_PASSWORD_SEND_VER_CODE);
                if (string.IsNullOrWhiteSpace(userName))
                {
                    ModelState.AddModelError(string.Empty, "用户名为空！");
                    return View("Forgotpassword");
                }
                if (!oldVerCode.ToLower().Equals(verCode))
                {
                    ModelState.AddModelError(string.Empty, "验证码不正确！");
                    return View("Forgotpassword");
                }
                var userEntity = service.QueryByUserName(userName);
                if (userEntity == null)
                {
                    ModelState.AddModelError(string.Empty, "账号不存在！");
                    return View("Forgotpassword");
                }
                var random = SecurityHelper.CreateRandomCode(6).ToLower();

                string token = MD5Helper.GetToken(userEntity.UserId + userEntity.Password + ConfigHelper.RESET_PASSWORD_SEND_VER_CODE + random).ToLower();
                await AppHttpContext.CacheService.AddAsync(token, random, TimeSpan.FromMinutes(ApplicationEnvironments.Site.SessionTimeout));
                Dictionary<string, string> valuePairs = new Dictionary<string, string>();
                valuePairs.Add(UserEntity.__Email,userEntity.Email);
                valuePairs.Add("ActiveCode", random);
                if (await eService.Send(userEntity.Email, "000002", valuePairs))
                {
                    return RedirectToAction("ChangePassword", "Account", new
                    {
                        userName = userName,
                        token = token
                    });
                }
                else
                {
                    ModelState.AddModelError(string.Empty,"邮箱不存在或者账号问题");
                }
               
            }
            return View();
        }
        public IActionResult ChangePassword(string userName, string password, string repassword, string token, string verCode, string mailVerCode)
        {
            ViewData["UserName"] = userName;
            ViewData["Token"] = token;
            ViewData["MailVerCode"] = mailVerCode;
            if (IsPost)
            {
                string strError = "";
                if (!service.ChangePwd(userName, password, repassword, token, verCode, mailVerCode, ref strError))
                {
                    ModelState.AddModelError(string.Empty, strError);
                    return View("ChangePassword");
                }
                return RedirectToAction("Index", "Login");
            }
            return View();
        }

        #endregion

        #region

        /// <summary>
        /// 验证用户名
        /// </summary>
        /// <param name="userAccount"></param>
        /// <returns></returns>

        public ActionResult ChkUserName(string userName,string userid = "")
        {
            string strError = "";
            bool flag = service.ChkUserName(userid, userName, ref strError);
            return Ok(flag);
        }


        public ActionResult ChkPhone(string phone,string userid = "")
        {
            string strError = "";
            bool flag = service.ChkUserPhone(userid, phone, ref strError);
            return Ok(flag);
        }

        public async Task<IActionResult> ChkEmail(string email,string userid="", string IsNotExist = "0")
        {
            string strError = "";
            if (IsNotExist.Equals("0"))
            {
                bool flag = service.ChkUserEmail(userid, email, ref strError);
                return Ok(flag);
            }
            if (!service.ChkUserEmail("", email, ref strError))
            {
                return Json(AjaxResult.Error(email+"已存在")) ;
            }
            var code = SecurityHelper.CreateRandomCode(6);
            await CacheService.AddAsync(MD5Helper.GetToken((ConfigHelper.EMAIL_SEND_ACTIVE_VER_CODE + email + code).ToLower()).ToLower(), code, TimeSpan.FromMinutes(5));
            Dictionary<string, string> valuePairs = new Dictionary<string, string>();
            valuePairs.Add(UserEntity.__Email, email);
            valuePairs.Add("ActiveCode", code);
            if (await eService.Send(email, "000001", valuePairs))
            {
                return Json(AjaxResult.Success(new { code = code }));
            }
            else
            {
                return Json(AjaxResult.Error("邮箱异常"));
            }
            //CookieHelper.AddCookie(Consts.EMAILActivationCode, code, DateTime.Now.AddMinutes(2));
            //var temp = new MailTemplateService().GetByCode(IsNotExist.Equals("0") ? "0001" : "0002");
            //string body = temp.MailTempContent;
            //new SendEmailService().Send(email, temp.MailTemplateTitle.Replace("@SiteName", ConfigHelper.SiteName), body.Replace("@SiteName", ConfigHelper.SiteName).Replace("@Email", email).Replace("@ActiveCode", code), ref strError);
           
        }

        [HttpPost]
    
        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="userEntity"></param>
        /// <returns></returns>
        public IActionResult SubmitRegister(UserEntity userEntity, string Verifycode)
        {

            ViewData["BindType"] = "1";
            string strError = "";
            if (ModelState.IsValid)
            {
                if (!service.Register(userEntity, ref strError, true, Verifycode))
                {
                    ModelState.AddModelError(string.Empty, strError);
                    return View("Register", userEntity);
                }
                return RedirectToAction("Index", "Login");
            }
            return View("Register", userEntity);

        }

        public IActionResult Register()
        {
            UserEntity userEntity = new UserEntity();
            ViewData["BindType"] = "1";
            return View(userEntity);
        }
        #endregion

        [HttpPost]
        public async Task<IActionResult> Login(UserEntity model, bool rememberMe, string returnUrl = null)
        {

            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {

                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, set lockoutOnFailure: true
                string strError = "";
                string token = "";
                var result = service.Login(model.UserName, model.Password, ref strError,ref token);
                if (result != null)
                {
                    var claims = new List<Claim>()
                    {
                        new Claim(ClaimTypes.Name,result.UserName) ,
                        new Claim(ClaimTypes.MobilePhone,result.Phone),
                        new Claim(ClaimTypes.Email,result.Email) ,
                         new Claim(ClaimTypes.Authentication,token) ,
                        new Claim(ClaimTypes.NameIdentifier,result.UserId.ToString())

                    };
                    await SignInAsync(claims, result.UserId.ToString(), token, rememberMe);
                    if (string.IsNullOrWhiteSpace(returnUrl))
                    {
                        return RedirectToAction("index", "home");
                    }
                    return Redirect(returnUrl);
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "用户名或者密码不正确！");
                    return View("Register", model);
                }
            }

            // If we got this far, something failed, redisplay form
            return View("Register", model);
        }
       
        [HttpPost]
       
        public JsonResult CheckLogin()
        {
           var result = this.GetUser<UserEntity>();
            if (result != null)
            {
                return Json(AjaxResult.Success(new { UserId=result.UserId, UserName = result.UserName, RealName = result.RealName, Sex = result.Sex, Phone = result.Phone, Email = result.Email }));
            }
            return Json(AjaxResult.Error("未登录"));


        }
    }
}